<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" center type="info" show-icon></el-alert>

      <!-- 步骤条区域  -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        ref="addGoodsFormRef"
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        label-width="120px"
      >
        <!-- tab栏区域 -->
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeEvent"
          @tab-click="tabChange"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="catelist"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 增加一个模板进行v-for遍历循环 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <template>
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
                </el-checkbox-group>
              </template>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="imgUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="imgHeaders"
              :on-success="handelSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片放大的对话框 -->
    <el-dialog title="预览图片" :visible.sync="priewDialog" width="50%">
      <img :src="imgPath" alt class="imgStyle" />
    </el-dialog>
  </div>
</template>

<script>
// 导入lodash组件
// import _ from 'lodash'
export default {
  data () {
    return {
      // 定义一个选择中的步骤
      activeIndex: '0',

      // 商品接收绑定数组
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器接收的数组
        goods_cat: [],

        // 定义一个接收图片信息的数组
        pics: [],
        goods_introduce: '',
        attrs: [] // 商品的参数（数组），包含 动态参数 和 静态属性
      },

      // 商品验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请先选择商品分类', trigger: 'blur' }
        ]
      },

      // 定义绑定级联选择器的接收分类参数数组
      catelist: [],

      // 级联选择器Props配置
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 动态参数数组
      manyTableData: [],

      // 定义一个静态参数数组
      onlyTableData: [],

      // 定义一个图片获取的基本路劲地址
      imgUrl: 'http://127.0.0.1:8888/api/private/v1/upload',

      // 为图片上传设置一个请求头
      imgHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 图片的临时路径
      imgPath: '',

      // 对话框的显示和隐藏
      priewDialog: false
    }
  },
  created () {
    // 调用商品分类的方法
    this.getCateData()
  },
  methods: {
    // 定义获取商品分类数据的方法
    async getCateData () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      this.catelist = res.data
    },

    // 触发事件
    handleChange () {
      // console.log(this.addGoodsForm.goods_cat)
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },

    // tab栏切换之前触发当的事件 不满足条件就不允许切换下一级
    beforeEvent (activeName, oldActiveName) {
      // console.log(activeName)
      // console.log(oldActiveName)
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请输入商品分类数据')
        return false
      }
    },

    // 点击tab栏切换tab-click:tab 被选中时触发的事件
    async tabChange () {
      // 当activeIndex='1' 证明是商品参数 才能发送请求
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // console.log(res.data)
        // 遍历数组 判断长度是不是0 是0返回一个空的数组 否则将数组转化为字符串
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        // console.log(res.data.attr_vals)
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyTableData = res.data
      }
    },

    // 上传成功触发的事件
    handelSuccess (response) {
      // console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
      console.log(this.addGoodsForm)
    },
    // 成功上传的图片触发的事件 处理图片预览
    handlePreview (file) {
      // console.log(file)
      this.imgPath = file.response.data.url
      this.priewDialog = true
    },

    // 点击删除触发的事件
    handleRemove (file) {
      // console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex(index => index.pic === filePath)
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm)
    },

    // 添加商品的方法
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入必填表单项目!')
        }

        // 添加的逻辑
        // 使用lodash来将goods_cat转换为需要的类型方法一
        // const form = _.cloneDeep(this.addGoodsForm)
        // form.goods_cat = form.goods_cat.join(',')
        // console.log(form)

        // 方法二
        const form = { ...this.addGoodsForm }
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form)

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const formInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(formInfo)
        })

        // 处理静态参数
        this.onlyTableData.forEach(item => {
          const formInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(formInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      // 分类id获取
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.imgStyle {
  width: 100%;
}
.btn {
  margin-top: 15px;
}
</style>
